<template>
	<view>
		<scroll-view id="scrollview" scroll-y :scroll-top="scrollTop" :scroll-with-animation="true" :style="{height:style.contentH + 'px'}">
			<!-- 聊天列表 -->
			<block v-for="(item,index) in list" :key="index">
				<chat-list :item="item" :index="index"></chat-list>
			</block>
		</scroll-view>
		<!-- 输入框 -->
		<chat-input @submit="submit"></chat-input>
	</view>
</template>

<script>
	import chatInput from "../../components/chat/chat-input.vue"
	import chatList from "../../components/chat/chat-list.vue"
	import {
		getChatTime
	} from "../../common/tools/time.js"
	export default {
		data() {
			return {
				scrollTop: 0,
				style: {
					contentH: 0,
					itemsH: 0
				},
				list: []
			};
		},
		methods: {
			// 初始化参数
			init() {
				uni.getSystemInfo({
					success: (res) => {
						let height = res.windowHeight - uni.upx2px(120);
						this.style.contentH = height
					}
				})
			},
			// 处理数据
			handleData() {
				let list = [{
						isme: true,
						userpic: "../../static/image/userpic/11.jpg",
						type: "text",
						data: "哈哈哈23333333333333333333333333333 333333333 333333333 333333333333333333",
						time: "1554970014"
					},
					{
						isme: false,
						userpic: "../../static/image/userpic/10.jpg",
						type: "img",
						data: "../../static/image/3.jpg",
						time: "1554970014"
					}
				]

				for (let i in list) {
					list[i].date = getChatTime(list[i].time, i > 0 ? list[i - 1].time : 0)
				}
				this.list = list
			},
			// 滚动条置于底部 在onReady 调用
			pageToBottom() {
				// 这里有问题: 不能正确获取高度,需要加延迟
				setTimeout(() => {
					let query = uni.createSelectorQuery()
					query.selectAll(".chat-item").boundingClientRect()
					query.exec((res) => {
						res[0].forEach(item => {
							this.style.itemsH += item.height
						})
						if (this.style.itemsH >= this.style.contentH) {
							this.scrollTop = this.style.itemsH
						}
					})
				})
			},
		  submit(text) {
				let now = new Date().getTime()
				let obj = {
					isme: true,
					userpic: "../../static/image/userpic/10.jpg",
					type: "text",
					time: now,
					data: text,
					date: getChatTime(now, this.list[this.list.length - 1].time)
				}
				this.list.push(obj)
				this.pageToBottom()
			}
		},
		components: {
			chatInput,
			chatList
		},
		onLoad() {
			this.init()
			this.handleData()
		},
		onReady() {
			this.pageToBottom()
		}
	}
</script>

<style lang="scss" scoped>

</style>
